package pub.cleangao.mqtt;

import com.vzenith.cloud.http.HttpClient;
import com.vzenith.cloud.http.HttpMethod;
import com.vzenith.cloud.http.HttpRequest;
import com.vzenith.cloud.http.HttpResponse;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import pub.cleangao.common.event.EventBus;
import pub.cleangao.common.event.ReactEvent;
import pub.cleangao.common.unique.IDWorker;
import java.util.function.Consumer;


@Component
public class MqttStubInitializer implements ApplicationRunner {

    @Value("${vzi-cloud.base-url}")
    private String baseUrl;

    @Value("${vzi-cloud.access-key-id}")
    private String accessKey;

    @Value("${vzi-cloud.access-key-secret}")
    private String accessKeySecret;

    @Autowired
    private MqttServer mqttServer;
    @Autowired
    private VzDevices vzDevices;
    @Autowired
    private VzMqttTopics vzMqttTopics;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        refreshMqttBrokerStub();
        EventBus.registerListenKey("mqtt:server-reconnect", new Consumer<ReactEvent>() {
            @Override
            public void accept(ReactEvent event) {
                refreshMqttBrokerStub();
            }
        });
    }

    public void refreshMqttBrokerStub() {
        HttpClient httpClient = new HttpClient(baseUrl, accessKey, accessKeySecret);
        HttpRequest request = new HttpRequest(HttpMethod.GET, "/openapi/v1/stp/clients/route");
        request.addParam("sid", IDWorker.nextIdChar());
        HttpResponse response = httpClient.doRequest(request);
        if (response.getStatus() == 200) {
            JSONObject jsonObject = new JSONObject(response.getBodyStr());
            String remoteAddr = jsonObject.getString("remote_addr");
            String password = jsonObject.getString("password");
            String host = jsonObject.getString("host");
            int port = jsonObject.getInt("port");
            String username = jsonObject.getString("username");
            String clientId = jsonObject.getString("clientid");
            mqttServer.setHost(host);
            mqttServer.setPort(port);
            mqttServer.setPassword(password);
            mqttServer.setUsername(username);
            mqttServer.setClientId(clientId);
            mqttServer.setLocalAddress(remoteAddr);
            System.out.println("MQTT Server 连接数据已初始化...");
            MqttClient mqttClient = null;
            try {
                mqttClient = new LocalMqttClient().connectToServer(mqttServer);
                System.out.println("本地MQTT客户端已连接至臻云 mqtt-broker");
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
            try {
                vzDevices.init();
                System.out.println("设备标识已完成初始化...");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try {
                vzMqttTopics.startListen(mqttClient);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("MQTT Client 启动完成.");


        }

    }


}
